/** file DefaultMixer.cpp
    author belot.nicolas
*/

#include "DefaultMixer.h"
#include <cmath>
#include <cassert>
#include <iostream>
namespace libtrckr {
	DefaultMixer::DefaultMixer():_tracks(0),_size(0),_mix(){

	}

	DefaultMixer::DefaultMixer(const DefaultMixer &d):_tracks(d._tracks),_size(d._size),_mix(d._mix){

	}

	DefaultMixer::~DefaultMixer(){
		std::cout << "seeya! " << std::endl;
	}

	uint DefaultMixer::tracks() const{
		return _tracks;
	};
	void DefaultMixer::tracks(uint tr){
		_tracks=tr;
	}

	uint DefaultMixer::length() const{
		return _size;
	}
	void DefaultMixer::length(uint len){
		_size=len;
		_mix = Buffer(len);
		_mix.channels(2);
	}

	void DefaultMixer::Append(Buffer& b, uint track, uint local=50, int gain=0){
		double data;
		double tgain=pow(10.0,gain/20.0);
		if(track < _tracks){			//we do something :)
			if(b.channels()>1){
				//setting mixleft and mixright.
				double mixleft= (local -50) / 100.0;// how many left we add
				double mixright = (100-local -50) / 100.0; // how many right we add..
				for(uint i=0;i<_size;i++){
					if(i<b.size()){
						if(mixleft > 0.){
							//we add mixleft from the right to the left!
							_mix.setChannel(0);
							b.setChannel(0);
							_mix[i]+=b[i];
							b.setChannel(1);
							_mix[i]+=(mixleft*b[i]);
							_mix.setChannel(1);
							_mix[i]+=(b[i] * 0.5+mixright);
						}else if(mixright>0.){
							//We add mixright from the left to the right!
							_mix.setChannel(1);
							b.setChannel(1);
							_mix[i]+=b[i];
							b.setChannel(0);
							_mix[i]+=(mixright*b[i]);
							_mix.setChannel(0);
							_mix[i]+=(b[i] * 0.5+mixleft);
	
						}else{
							//nothing to do	
							b.setChannel(0);_mix.setChannel(0);
							_mix[i]+=b[i];
							b.setChannel(1);_mix.setChannel(1);
							_mix[i]+=b[i];
						}
					}else{
						_mix.setChannel(0);
						_mix[i]=0.;
						_mix.setChannel(1);
						_mix[i]=0.;

					}
					/*data=0.0;
					b.setChannel(0);
					
					while(b.hasNextChannel()){
						data+=b[i];			
						b.nextChannel();
					}
					//data=(data*tgain/b.channels())/_tracks;
					data*=tgain/_tracks;
					_mix.setChannel(0);
					_mix[i]+=(local/100.0)*data;
					_mix.setChannel(1);
					_mix[i]+=(1.0 - (local/100.0)) *data; */
				}
			
			}else{
				b.setChannel(0);
				for(uint i=0;i<_size;i++){
					if(i>=b.size()){
						data=0.0;
					}else{
						data=b[i]*tgain;
					}
					_mix.setChannel(0);
					_mix[i]+=(local/100.0)*data;
					_mix.setChannel(1);
					_mix[i]+=(1.0 - (local/100.0)) *data; 
				}
			}
		}
	}//append the buffer, track, % left
	
	Buffer DefaultMixer::Mixed(){
		Buffer tmp=_mix;
		_mix.flush();
		return tmp;
	}

}
